<template>
  <div class="echart" ref="mychart"></div>
</template>

<script setup>
import { ref, watch, onMounted, onBeforeUnmount } from "vue";
import * as echarts from "echarts";

// Props 接收
const props = defineProps({
  options: {
    type: Object,
    default: () => ({
      title: {
        text: "ECharts 示例",
      },
      tooltip: {},
      legend: {
        data: ["销量"],
      },
      xAxis: {
        data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"],
      },
      yAxis: {},
      series: [
        {
          name: "销量",
          type: "bar",
          data: [5, 20, 36, 10, 10, 20],
        },
      ],
    }),
  },
  autoResize: {
    type: Boolean,
    default: true,
  },
});

// emits 声明
const emit = defineEmits(["chart-click"]);

const mychart = ref(null);
let myChart = null;
let resizeTimeout = null;

// 初始化图表
const initEcharts = () => {
  if (!myChart && mychart.value) {
    myChart = echarts.init(mychart.value);
    updateChart(props.options);
    addClickListener();
  }
};

// 更新图表配置
const updateChart = (options) => {
  if (myChart) {
    myChart.setOption(options, true);
  }
};

// resize 事件
const handleResize = () => {
  if (resizeTimeout) clearTimeout(resizeTimeout);
  resizeTimeout = setTimeout(() => {
    myChart?.resize();
  }, 200);
};

const addResizeListener = () => {
  window.addEventListener("resize", handleResize);
};

const removeResizeListener = () => {
  window.removeEventListener("resize", handleResize);
};

// 图表点击事件绑定
const addClickListener = () => {
  if (myChart) {
    myChart.on("click", handleChartClick);
  }
};

const removeClickListener = () => {
  if (myChart) {
    myChart.off("click", handleChartClick);
  }
};

const handleChartClick = (params) => {
  emit("chart-click", params);
};

// 监听 options 更新
watch(
  () => props.options,
  (newOptions) => {
    updateChart(newOptions);
  },
  { deep: true }
);

// 生命周期
onMounted(() => {
  initEcharts();
  if (props.autoResize) {
    addResizeListener();
  }
});

onBeforeUnmount(() => {
  removeClickListener();
  myChart?.dispose();
  myChart = null;
  if (props.autoResize) {
    removeResizeListener();
  }
});
</script>

<style scoped>
.echart {
  width: 100%;
  height: 100%;
}
</style>
